import { useEffect } from "react"
import Web3 from 'web3'
import tokenJson from '../build/MinminToken.json'
import exchangeJson from '../build/Exchange.json'
import Balance from "./Balance"
import Order from "./Orders"
import { useDispatch } from 'react-redux'
import { loadBalacnceData } from "../redux/slices/balanceSlice"
import { loadAllOrderData, loadCancelOrderData, loadFillOrderData } from "../redux/slices/orderSlice"

export default function Home() {
  let isFilled = false
  const dispatch = useDispatch()
  useEffect(() => {
    async function start() {
      // 获取链接后的合约
      const web = await initWeb()
      // 全局挂载
      window.web = web
      console.log(web)
      // 获取资产信息
      dispatch(loadBalacnceData(web))
      // 获取订单信息
      dispatch(loadCancelOrderData(web))
      dispatch(loadFillOrderData(web))
      dispatch(loadAllOrderData(web))
      // 监听
      web.exchange.events.Deposit({}, () => {
        dispatch(loadBalacnceData(web))
      })
      web.exchange.events.WithDraw({}, () => {
        dispatch(loadBalacnceData(web))
      })
      web.exchange.events.Order({}, (error, event) => {
        dispatch(loadAllOrderData(web))
      })
      web.exchange.events.Cancel({}, (error, event) => {
        dispatch(loadCancelOrderData(web))
      })
      web.exchange.events.Fill({}, (error, event) => {
        dispatch(loadFillOrderData(web))
        dispatch(loadBalacnceData(web))
      })
    }

    if (!isFilled) {
      start()
    }
    
    return () => { isFilled = true }
  }, [])

  async function initWeb() {
    const web3 = new Web3(Web3.givenProvider || 'http://localhost:8545')
    // 授权
    const accounts = await web3.eth.requestAccounts()
    // 获取 netWorkId
    const networkId = await web3.eth.net.getId()
    // token
    const tokenAbi = tokenJson.abi
    const tokenAddress = tokenJson.networks[networkId].address
    const token = await new web3.eth.Contract(tokenAbi, tokenAddress)
    // exchange
    const exchangeAbi = exchangeJson.abi
    const exchangeAddress = exchangeJson.networks[networkId].address
    const exchange = await new web3.eth.Contract(exchangeAbi, exchangeAddress)

    // ethAddress
    const ethAddress = '0x0000000000000000000000000000000000000000'
    
    return {
      web3,
      account: accounts[0],
      token,
      exchange,
      ethAddress
    }

  }

  return (
    <>
      <Balance></Balance>
      <Order></Order>
    </>
  )
}